﻿#include "configsetting.h"
#include "ui_configsetting.h"

//#pragma execution_character_set("utf-8")

ConfigSetting::ConfigSetting(QVector<Target*>* pDevices, Target* pSelectDevice, QString* pFilePath, QWidget *parent) :
    QDialog(parent),
    ui(new Ui::ConfigSetting)
{
    ui->setupUi(this);


    if(pFilePath)
    {
       ui->filePath->setText(*pFilePath);
    }

    // 将配置文件中设备添加到连接设备下拉框选项中
    for(int i = 0; i < pDevices->size(); ++i)
    {
        ui->deviceSelect->addItem((*pDevices)[i]->getDeviceName());
    }

    // 判断连接目标的默认显示
    if(NULL == pSelectDevice)
    {
        // 下拉框默认显示第0个选项
        ui->deviceSelect->setCurrentIndex(0);
    }
    else
    {
        // 下拉框显示上次选择的内容
        ui->deviceSelect->setCurrentText(pSelectDevice->getDeviceName());
    }


    // 新建文件选择对话框
    QFileDialog* fileDialog = new QFileDialog(this);

    // 配置文件选择按钮功能
    connect(ui->selectButton, &QToolButton::clicked, this, [=](){
        fileDialog->setDirectory(QApplication::applicationDirPath());
        QString path = fileDialog->getOpenFileName(this, QString("选择配置文件"), NULL, QString("xml file(*.xml)"));
        if (!path.isEmpty())ui->filePath->setText(path);
    });

    // 确认按钮功能
    connect(ui->confirm, &QPushButton::clicked, this, [=](){
        for(int i = 0; i < pDevices->size(); ++i)
        {
            if(0 == (*pDevices)[i]->getDeviceName().compare(ui->deviceSelect->currentText()))
            {
                emit confirm(*pDevices->at(i), ui->filePath->text());                                                     // 发送选择对象和文件路径
                break;
            }
        }
        this->close();                                                                                                  // 关闭对话框
        if(fileDialog)
        {
            delete fileDialog;                                                                                          // 删除文件对话框
        }
    });

    //取消按钮功能
    connect(ui->cancel, &QPushButton::clicked, this, [=](){
        this->close();                                                                                                  // 关闭对话框
        if(fileDialog)
        {
            delete fileDialog;                                                                                          // 删除文件对话框
        }
    });

}

ConfigSetting::~ConfigSetting()
{
    delete ui;
}


